<template>
  <view class="page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="40" color="#007aff"></uni-icons>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 商品内容 -->
    <view v-else-if="product.id" class="product-content">
    <!-- 商品图片轮播 -->
    <swiper class="product-swiper" circular indicator-dots indicator-color="rgba(255, 255, 255, 0.6)" indicator-active-color="#ffffff">
      <swiper-item v-for="(image, index) in product.images" :key="index">
        <image class="product-image" :src="image" mode="aspectFill"></image>
      </swiper-item>
    </swiper>

    <!-- 商品基本信息 -->
    <view class="product-info">
      <view class="product-title">{{ product.title }}</view>
      <view class="product-subtitle">{{ product.subtitle }}</view>
      
      <!-- 价格区域 -->
      <view class="price-section">
        <view class="current-price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ product.price }}</text>
        </view>
        <view class="original-price" v-if="product.originalPrice">
          <text class="original-text">¥{{ product.originalPrice }}</text>
        </view>
        <view class="discount-tag" v-if="product.discount">
          {{ product.discount }}折
        </view>
      </view>

      <!-- 优惠信息 -->
      <view class="promotion-section" v-if="product.promotions && product.promotions.length > 0">
        <view class="promotion-item" v-for="(promo, index) in product.promotions" :key="index">
          <text class="promo-tag">{{ promo.type }}</text>
          <text class="promo-text">{{ promo.text }}</text>
        </view>
      </view>

      <!-- 库存和销量 -->
      <view class="stock-sales">
        <text class="stock-text">库存{{ product.stock }}件</text>
        <text class="sales-text">已售{{ product.sales }}件</text>
      </view>
    </view>

    <!-- 规格选择 -->
    <view class="spec-section" @tap="showSpecModal">
      <view class="spec-header">
        <text class="spec-title">选择规格</text>
        <view class="spec-selected">
          <text class="selected-text">{{ selectedSpecs }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="detail-header">
        <text class="detail-title">商品详情</text>
      </view>
      <view class="detail-content">
        <image v-for="(detailImg, index) in product.detailImages" :key="index" 
               class="detail-image" :src="detailImg" mode="widthFix"></image>
      </view>
    </view>

    <!-- 评价区域 -->
    <view class="review-section">
      <view class="review-header" @tap="goToReviews">
        <text class="review-title">商品评价</text>
        <view class="review-summary">
          <text class="review-rate">{{ product.reviewRate }}%好评</text>
          <text class="review-count">({{ product.reviewCount }}条)</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- 精选评价 -->
      <view class="review-item" v-for="(review, index) in product.reviews.slice(0, 2)" :key="index">
        <view class="review-user">
          <image class="user-avatar" :src="review.avatar" mode="aspectFill"></image>
          <text class="user-name">{{ review.username }}</text>
          <view class="review-stars">
            <uni-icons v-for="star in 5" :key="star" 
                      :type="star <= review.rating ? 'star-filled' : 'star'" 
                      size="12" :color="star <= review.rating ? '#FFD700' : '#E0E0E0'"></uni-icons>
          </view>
        </view>
        <text class="review-content">{{ review.content }}</text>
        <view class="review-images" v-if="review.images && review.images.length > 0">
          <image v-for="(img, imgIndex) in review.images" :key="imgIndex" 
                 class="review-img" :src="img" mode="aspectFill"></image>
        </view>
        <text class="review-time">{{ review.time }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-icons">
        <view class="action-item" @tap="toggleFavorite">
          <uni-icons :type="isFavorite ? 'heart-filled' : 'heart'" 
                    size="24" :color="isFavorite ? '#FF4757' : '#666'"></uni-icons>
          <text class="action-text">收藏</text>
        </view>
        <view class="action-item" @tap="goToCart">
          <uni-icons type="cart" size="24" color="#666"></uni-icons>
          <text class="action-text">购物车</text>
          <view class="cart-badge" v-if="cartCount > 0">
            <text class="badge-text">{{ cartCount > 99 ? '99+' : cartCount }}</text>
          </view>
        </view>
      </view>
      
      <view class="buy-buttons">
        <button class="add-cart-btn" @tap="addToCart">加入购物车</button>
        <button class="buy-now-btn" @tap="buyNow">立即购买</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <uni-popup ref="specPopup" type="bottom">
      <view class="spec-modal">
        <view class="modal-header">
          <view class="product-brief">
            <image class="brief-image" :src="product.images[0]" mode="aspectFill"></image>
            <view class="brief-info">
              <text class="brief-price">¥{{ product.price }}</text>
              <text class="brief-stock">库存{{ product.stock }}件</text>
            </view>
          </view>
          <uni-icons type="closeempty" size="24" color="#999" @tap="closeSpecModal"></uni-icons>
        </view>
        
        <!-- 规格选择项 -->
        <view class="spec-options">
          <view class="spec-group" v-for="(spec, specIndex) in product.specs" :key="specIndex">
            <text class="spec-name">{{ spec.name }}</text>
            <view class="spec-values">
              <view v-for="(value, valueIndex) in spec.values" :key="valueIndex"
                    class="spec-value" 
                    :class="{ 'selected': selectedSpecValues[specIndex] === valueIndex }"
                    @tap="selectSpec(specIndex, valueIndex)">
                <text class="spec-value-text">{{ value }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 数量选择 -->
        <view class="quantity-section">
          <text class="quantity-label">数量</text>
          <view class="quantity-control">
            <button class="quantity-btn" :disabled="quantity <= 1" @tap="decreaseQuantity">-</button>
            <text class="quantity-value">{{ quantity }}</text>
            <button class="quantity-btn" :disabled="quantity >= product.stock" @tap="increaseQuantity">+</button>
          </view>
        </view>
        
        <button class="confirm-btn" @tap="confirmSpec">确定</button>
      </view>
    </uni-popup>
    </view>
    
    <!-- 商品不存在提示 -->
    <view v-else class="empty-container">
      <uni-icons type="info" size="60" color="#999"></uni-icons>
      <text class="empty-text">商品不存在或已下架</text>
    </view>
  </view>
</template>

<script>
import { productApi, apiUtils } from '@/utils/api.js'

export default {
  data() {
    return {
      product: {},
      loading: true,
      selectedSpecValues: [], // 选中的规格索引
      quantity: 1,
      isFavorite: false,
      cartCount: 0
    }
  },
  
  computed: {
    selectedSpecs() {
      if (this.selectedSpecValues.length === 0) {
        return '请选择规格'
      }
      let specs = []
      this.product.specs.forEach((spec, index) => {
        if (this.selectedSpecValues[index] !== undefined) {
          specs.push(spec.values[this.selectedSpecValues[index]])
        }
      })
      return specs.join('，')
    }
  },
  
  onLoad(options) {
    // 根据传入的商品ID加载商品数据
    if (options.id) {
      this.loadProductDetail(options.id)
    } else {
      uni.showToast({
        title: '商品ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
    
    // 初始化购物车数量
    this.loadCartCount()
  },
  
  methods: {
    /**
     * 加载商品详情数据
     * @param {number} id 商品ID
     */
    async loadProductDetail(id) {
      try {
        this.loading = true
        
        const productData = await productApi.getProductDetail(id)
        
        // 处理商品数据
        this.product = this.processProductDetail(productData)
        
        // 初始化规格选择
        this.selectedSpecValues = new Array(this.product.specs?.length || 0)
        
      } catch (error) {
        console.error('加载商品详情失败:', error)
        uni.showToast({
          title: '商品加载失败',
          icon: 'none'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 处理商品详情数据格式
     * @param {Object} data 原始商品数据
     * @returns {Object} 处理后的商品数据
     */
    processProductDetail(data) {
      return {
        id: data.id,
        title: data.title,
        subtitle: data.subtitle,
        price: apiUtils.formatPrice(data.price),
        originalPrice: data.originalPrice ? apiUtils.formatPrice(data.originalPrice) : null,
        discount: data.discount,
        stock: data.stock,
        sales: apiUtils.formatSales(data.sales),
        images: apiUtils.processImageUrl(data.imageList || []),
        promotions: data.promotions || [],
        specs: this.processSpecs(data.specs || []),
        detailImages: apiUtils.processImageUrl(data.detailImageList || []),
        reviewRate: data.reviewRate,
        reviewCount: data.reviewCount,
        reviews: this.processReviews(data.reviews || [])
      }
    },
    
    /**
     * 处理商品规格数据
     * @param {Array} specs 原始规格数据
     * @returns {Array} 处理后的规格数据
     */
    processSpecs(specs) {
      return specs.map(spec => ({
        name: spec.name,
        values: spec.valueList || []
      }))
    },
    
    /**
     * 处理商品评价数据
     * @param {Array} reviews 原始评价数据
     * @returns {Array} 处理后的评价数据
     */
    processReviews(reviews) {
      return reviews.map(review => ({
        username: review.username,
        avatar: apiUtils.processImageUrl(review.avatar),
        rating: review.rating,
        content: review.content,
        images: apiUtils.processImageUrl(review.imageList || []),
        time: review.time
      }))
    },
    
    loadCartCount() {
      // 模拟加载购物车数量
      this.cartCount = uni.getStorageSync('cartCount') || 0
    },
    
    showSpecModal() {
      this.$refs.specPopup.open()
    },
    
    closeSpecModal() {
      this.$refs.specPopup.close()
    },
    
    selectSpec(specIndex, valueIndex) {
      this.$set(this.selectedSpecValues, specIndex, valueIndex)
    },
    
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    increaseQuantity() {
      if (this.quantity < this.product.stock) {
        this.quantity++
      }
    },
    
    confirmSpec() {
      this.closeSpecModal()
    },
    
    toggleFavorite() {
      this.isFavorite = !this.isFavorite
      uni.showToast({
        title: this.isFavorite ? '已收藏' : '已取消收藏',
        icon: 'none'
      })
    },
    
    goToCart() {
      uni.navigateTo({
        url: '/pages/cart/cart'
      })
    },
    
    async addToCart() {
      // 检查是否选择了规格
      if (this.selectedSpecValues.length < this.product.specs.length) {
        this.showSpecModal()
        return
      }
      
      try {
        // 检查库存
        const hasStock = await productApi.checkStock(this.product.id, this.quantity)
        
        if (!hasStock) {
          uni.showToast({
            title: '库存不足',
            icon: 'none'
          })
          return
        }
        
        // 添加到购物车逻辑
        this.cartCount++
        uni.setStorageSync('cartCount', this.cartCount)
        
        uni.showToast({
          title: '已加入购物车',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('添加购物车失败:', error)
        uni.showToast({
          title: '添加失败，请重试',
          icon: 'none'
        })
      }
    },
    
    buyNow() {
      // 检查是否选择了规格
      if (this.selectedSpecValues.length < this.product.specs.length) {
        this.showSpecModal()
        return
      }
      
      // 立即购买逻辑
      uni.navigateTo({
        url: '/pages/order/confirm'
      })
    },
    
    goToReviews() {
      uni.navigateTo({
        url: `/pages/product/reviews?id=${this.product.id}`
      })
    }
  }
}
</script>

<style>
.page {
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  background-color: #fff;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  background-color: #fff;
}

.empty-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

/* 商品内容容器 */
.product-content {
  background-color: #f5f5f5;
}

.product-swiper {
  width: 100%;
  height: 750rpx;
  background-color: #fff;
}

.product-image {
  width: 100%;
  height: 100%;
}

.product-info {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.product-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  line-height: 44rpx;
  margin-bottom: 10rpx;
}

.product-subtitle {
  font-size: 28rpx;
  color: #666;
  line-height: 40rpx;
  margin-bottom: 20rpx;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
}

.current-price {
  display: flex;
  align-items: baseline;
  margin-right: 20rpx;
}

.price-symbol {
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
}

.price-value {
  font-size: 48rpx;
  color: #ff4757;
  font-weight: bold;
}

.original-price {
  margin-right: 20rpx;
}

.original-text {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
}

.discount-tag {
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.promotion-section {
  margin-bottom: 20rpx;
}

.promotion-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.promo-tag {
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
}

.promo-text {
  font-size: 24rpx;
  color: #666;
}

.stock-sales {
  display: flex;
  justify-content: space-between;
}

.stock-text, .sales-text {
  font-size: 24rpx;
  color: #999;
}

.spec-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.spec-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.spec-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.spec-selected {
  display: flex;
  align-items: center;
}

.selected-text {
  font-size: 24rpx;
  color: #999;
  margin-right: 10rpx;
}

.detail-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.detail-header {
  margin-bottom: 20rpx;
}

.detail-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.detail-image {
  width: 100%;
  margin-bottom: 20rpx;
}

.review-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.review-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.review-summary {
  display: flex;
  align-items: center;
}

.review-rate {
  font-size: 24rpx;
  color: #ff4757;
  margin-right: 10rpx;
}

.review-count {
  font-size: 24rpx;
  color: #999;
  margin-right: 10rpx;
}

.review-item {
  border-top: 1px solid #f0f0f0;
  padding-top: 20rpx;
  margin-bottom: 20rpx;
}

.review-user {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 15rpx;
}

.user-name {
  font-size: 24rpx;
  color: #333;
  margin-right: 15rpx;
}

.review-stars {
  display: flex;
}

.review-content {
  font-size: 26rpx;
  color: #333;
  line-height: 36rpx;
  margin-bottom: 10rpx;
}

.review-images {
  display: flex;
  margin-bottom: 10rpx;
}

.review-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 10rpx;
}

.review-time {
  font-size: 22rpx;
  color: #999;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-icons {
  display: flex;
  margin-right: 30rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 40rpx;
  position: relative;
}

.action-text {
  font-size: 20rpx;
  color: #666;
  margin-top: 5rpx;
}

.cart-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #ff4757;
  color: #fff;
  border-radius: 50%;
  min-width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.badge-text {
  font-size: 18rpx;
}

.buy-buttons {
  flex: 1;
  display: flex;
}

.add-cart-btn {
  flex: 1;
  height: 80rpx;
  background-color: #ffa726;
  color: #fff;
  border: none;
  border-radius: 40rpx 0 0 40rpx;
  font-size: 28rpx;
  margin-right: 2rpx;
}

.buy-now-btn {
  flex: 1;
  height: 80rpx;
  background-color: #ff4757;
  color: #fff;
  border: none;
  border-radius: 0 40rpx 40rpx 0;
  font-size: 28rpx;
}

/* 规格弹窗样式 */
.spec-modal {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
  max-height: 80vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30rpx;
}

.product-brief {
  display: flex;
  align-items: center;
  flex: 1;
}

.brief-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.brief-info {
  flex: 1;
}

.brief-price {
  font-size: 32rpx;
  color: #ff4757;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.brief-stock {
  font-size: 24rpx;
  color: #999;
}

.spec-options {
  margin-bottom: 30rpx;
}

.spec-group {
  margin-bottom: 30rpx;
}

.spec-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  display: block;
  margin-bottom: 15rpx;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
}

.spec-value {
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  padding: 15rpx 25rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
}

.spec-value.selected {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.spec-value-text {
  font-size: 26rpx;
  color: #333;
}

.spec-value.selected .spec-value-text {
  color: #ff4757;
}

.quantity-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.quantity-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  border: 1px solid #e0e0e0;
  background-color: #fff;
  color: #333;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-btn:disabled {
  color: #ccc;
  border-color: #f0f0f0;
}

.quantity-value {
  width: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  background-color: #ff4757;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
}
</style>